let listLoad = require('../../common/mixinList')
Page({
    behaviors: [listLoad],
    data: {
        navInfo: '',
        supplier_type: '', //供应商类型 0普通供应商  1批发供应商
        tab_active: 0,
        reqUrl: '/supplier/product/items',
        searchText: '',
        toExamine: true, //添加商品、修改商品是否需要审核
        tabs: [{
            title: '上架中',
            buttons: [{
                name: '下架商品',
                mark: 'down'
            }, {
                name: '编辑商品',
                mark: 'editGoods'
            }, {
                name: '报名专区',
                mark: 'signUp'
            }]
        }, {
            title: '待上架',
            buttons: [{
                name: '上架商品',
                mark: 'put'
            }, {
                name: '编辑商品',
                mark: 'editGoods'
            }, {
                name: '报名专区',
                mark: 'signUp'
            }, {
                name: '删除商品',
                mark: 'delGoods'
            }, ]
        }, {
            title: '审核中',
            buttons: [{
                name: '取消审核',
                mark: 'cancelExamine'
            }]
        }, {
            title: '未通过',
            buttons: [{
                name: '提交重审',
                mark: 'retrial'
            }]
        }],
        scrollTop: 0,
        open: false, //展示报名弹出层
        product_index: '', //报名活动的产品id
        choose: [{
                name: '特惠',
                choosed: false
            },
            //  {
            //     name: '新品',
            //     choosed: false
            // }, 
            {
                name: '品质',
                choosed: false
            }, {
                name: '视频',
                choosed: false
            }
        ], //报名选中项的索引

        showModifyPrice: false, //显示批量调价
        radio: 0, //0减价  1加价 
        sourceActive: 0, //调价类型 0普通价  1批发价
        ModifyPrice: '', //改价的金额
        ModifyPriceErr: false,
        modifyPriceLoading: false,

        enableToDetail: true, //允许前往商品详情（防止输入框失焦时误触）

    },
    onLoad: function(options) {
        this.setData({
            navInfo: getApp().globalData.navInfo
        })
        this.getList(true)
        options.supplier_type ? this.setData({ supplier_type: Number(options.supplier_type) }) : this.getDetail()
    },
    getParamsData() { //页面特殊的请求参数，需要时在页面内覆盖此方法，默认返回{}
        let type
        switch (this.data.tab_active) {
            case 0:
                type = 3
                break;
            case 1:
                type = 2
                break;
            case 2:
                type = 1
                break;
            case 3:
                type = 4
                break;
        }
        return { type, so: this.data.searchText }
    },
    onTabChange(event) {
        let actionOptions
        if (event.detail.index === 0) {
            actionOptions = [{ name: '批量下架', field: 'down' }, { name: '批量调价', field: 'modifyPrice' }]
        }
        if (event.detail.index === 1) {
            actionOptions = [{ name: '批量上架', field: 'up' }]
        }
        this.setData({
            list: [],
            empty: true,
            tab_active: event.detail.index,
            scrollTop: 0,
            actionOptions
        })
        this.getList(true)


    },
    /**获取供应商详情信息 */
    getDetail() {
        this.request({
            url: '/supplier/supplier/detail'
        }, res => {
            this.setData({ supplier_type: res.data.supplier_type })
        }, res => {
            if (res.code == 13003) {
                this.redirect_login()
            }
        })
    },
    operation({ mark }) {
        const { index, operation } = mark
        if (index == undefined) return
        if (operation === 'cancelExamine') return this.cancelExamine(index)
        if (operation === 'delGoods') return this.delGoods(index)
        if (operation === 'signUp') return this.signUp(index)
        if (operation === 'editGoods') return this.editGoods(index)
        if (operation === 'put') return this.putOrDown(index, 1)
        if (operation === 'down') return this.putOrDown(index, 0)
        if (operation === 'retrial') return this.cancelExamine(index, true)
        this.delay(() => {
            if (!this.data.enableToDetail) return
            wx.navigateTo({
                url: `/pages/good_detail/index?product_id=${this.data.list[index].product_id}&active=${this.data.tab_active}`,
                events: {
                    splice: () => { //详情页部分操作成功此页裁剪一条
                        let data = this.data.list
                        data.splice(index, 1)
                        this.setData({ list: data, empty: data.length === 0 })
                    },
                    refresh: () => { // 编辑商品成功，此页面刷新
                        this.getList(true)
                    }
                }
            })
        }, 100)
    },
    //取消审核、重审
    cancelExamine(index, retrial) {
        wx.$dialog.confirm({
            title: '提示',
            message: `您确定${retrial?'重新提交':'取消'}审核吗？`,
            theme: 'round-button',
            beforeClose: (action) => new Promise((resolve) => {
                if (action === 'confirm') {
                    return this.request({
                        url: '/supplier/product/verify',
                        method: 'POST',
                        data: {
                            product_id: this.data.list[index].product_id,
                            status: retrial ? '1' : '2'
                        }
                    }, () => {
                        resolve(true)
                        wx.showToast({
                            title: retrial ? '提交成功' : '取消成功',
                            icon: 'success'
                        })
                        let data = this.data.list
                        data.splice(index, 1)
                        this.setData({ list: data, empty: data.length === 0 })
                    }, () => {
                        resolve()
                    })
                }
                resolve(true);
            })
        })
    },
    //删除商品
    delGoods(index) {
        wx.$dialog.confirm({
            title: '提示',
            message: `您确定删除该商品吗？`,
            theme: 'round-button',
            beforeClose: (action) => new Promise((resolve) => {
                if (action === 'confirm') {
                    return this.request({
                        url: '/supplier/product/delete',
                        method: 'POST',
                        data: {
                            product_id: this.data.list[index].product_id
                        }
                    }, () => {
                        resolve(true)
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success'
                        })
                        let data = this.data.list
                        data.splice(index, 1)
                        this.setData({ list: data, empty: data.length === 0 })
                    }, () => {
                        resolve()
                    })
                }
                resolve(true);
            })
        })
    },
    //报名专区
    signUp(index) {
        this.setData({
            product_index: index,
            open: true
        })
    },
    //关闭报名专区弹出层
    closeSignup() {
        this.setData({
            open: false,
            product_index: '',
            choose: [{
                    name: '特惠',
                    choosed: false
                },
                //  {
                //     name: '新品',
                //     choosed: false
                // }
                {
                    name: '品质',
                    choosed: false
                }, {
                    name: '视频',
                    choosed: false
                }
            ]
        })
    },
    //选择报名选项
    onChooseChange({ currentTarget }) {
        const { index } = currentTarget.dataset
        const { choosed } = this.data.choose[index]
        this.setData({
            choose: [{
                    name: '特惠',
                    choosed: false
                },
                //  {
                //     name: '新品',
                //     choosed: false
                // }
                {
                    name: '品质',
                    choosed: false
                }, {
                    name: '视频',
                    choosed: false
                }
            ],
            ['choose[' + index + '].choosed']: !choosed
        })
    },
    //点击确认报名
    confirm_signup() {
        const { choose, product_index, list } = this.data
        const type = choose.findIndex(item => {
            return item.choosed
        })
        this.closeSignup()
        if (type === -1) return
        let reqType = type
        if (type === 0) {
            reqType += 1
        } else {
            reqType += 2
        }
        this.request({
            url: '/supplier/product/activity/apply',
            method: 'POST',
            loadingTip: '报名中',
            data: {
                product_id: list[product_index].product_id,
                type: reqType
            }
        }, () => {
            wx.showToast({
                title: '报名成功',
                icon: 'success'
            })
        })
    },
    //编辑商品
    editGoods(index) {
        wx.navigateTo({
            url: `/pages/goods_add/index?id=${this.data.list[index].product_id}&supplier_type=${this.data.supplier_type}`,
            events: {
                // 编辑成功，此页面刷新
                acceptDataFromOpenedPage: () => {
                    this.getList(true)
                }
            }
        })
    },
    //上下架商品
    putOrDown(index, type) {
        wx.$dialog.confirm({
            title: '提示',
            message: `您确定${['下架','上架'][type]}该商品吗？`,
            theme: 'round-button',
            beforeClose: (action) => new Promise((resolve) => {
                if (action === 'confirm') {
                    return this.request({
                        url: '/supplier/product/onSale',
                        method: 'POST',
                        data: {
                            product_id: this.data.list[index].product_id,
                            status: type + 1
                        }
                    }, () => {
                        resolve(true)
                        wx.showToast({
                            title: ['下架成功', '上架成功'][type],
                            icon: 'success'
                        })
                        let data = this.data.list
                        data.splice(index, 1)
                        this.setData({ list: data, empty: data.length === 0 })
                    }, () => {
                        resolve()
                    })
                }
                resolve(true);
            })
        })
    },
    /**验证金额输入 */
    formatter(value) {
        value = value.toString()
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        if (value.indexOf(".") < 0 && value != "") { //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            value = parseFloat(value);
        }
        value = parseFloat(value)
        if (Number.isNaN(value)) return ''
        return value
    },
    //前往添加商品
    toAdd() {
        wx.navigateTo({
            url: `/pages/goods_add/index?supplier_type=${this.data.supplier_type}`,
            events: {
                // 添加成功，此页面刷新
                acceptDataFromOpenedPage: () => {
                    this.getList(true)
                }
            }
        })
    },
    //子组件触发此页修改普通供应价
    setCostPrice(e) {
        const { index, cost_price } = e.detail
        this.setData({
            ['list[' + index + '].cost_price']: cost_price
        })
    },
    //子组件失去焦点触发修改普通供应价格
    editPrice(e) {
        const { index, product_id, cost_price } = e.detail
        this.request({
            url: '/supplier/product/setPrice',
            method: 'POST',
            data: {
                product_id,
                cost_price
            }
        }, () => {
            wx.showToast({
                title: '修改成功',
                icon: 'success'
            })
            this.setData({
                ['list[' + index + '].cost_price']: cost_price
            })
        }, () => {
            wx.showToast({
                title: '修改失败',
                icon: 'error'
            })
        })
    },
    //子组件触发此页修改批发供应价
    setWholesalePrice(e) {
        const { index, wholesalePrice } = e.detail
        this.setData({
            ['list[' + index + '].purchase_price']: wholesalePrice
        })
    },
    //子组件失去焦点触发修改批发供应价
    editWholesalePrice(e) {
        const { index, product_id, wholesalePrice } = e.detail
        this.request({
            url: '/supplier/product/setPurchase',
            method: 'POST',
            data: {
                product_id,
                purchase_price: wholesalePrice
            }
        }, () => {
            wx.showToast({
                title: '修改成功',
                icon: 'success'
            })
            this.setData({
                ['list[' + index + '].purchase_price']: wholesalePrice
            })
        }, () => {
            wx.showToast({
                title: '修改失败',
                icon: 'error'
            })
        })
    },
    //子组件触发修改库存
    editSku(e) {
        const { index, product_id, sku } = e.detail
        this.request({
            url: '/supplier/product/setSkuNew',
            method: 'POST',
            data: {
                product_id,
                sku
            }
        }, () => {
            wx.showToast({
                title: '修改成功',
                icon: 'success'
            })
            this.setData({
                ['list[' + index + '].sku']: sku
            })
        }, () => {
            wx.showToast({
                title: '修改失败',
                icon: 'error'
            })
        })
    },
    //批量上下架
    selectBatchAction(e) {
        const { field } = e.currentTarget.dataset

        if (this.data.list.length === 0) return wx.showToast({
            title: '暂无商品',
            icon: 'none'
        })

        wx.$dialog.confirm({
            title: '提示',
            message: `您确定${field==='up'?'上架':'下架'}所有商品吗？`,
            theme: 'round-button',
            beforeClose: (action) => new Promise((resolve) => {
                if (action === 'confirm') {
                    const pids = this.data.list.map(item => {
                        return item.product_id
                    })
                    return this.request({
                        url: '/supplier/product/batch',
                        method: 'POST',
                        data: {
                            pids,
                            status: field === 'up' ? 2 : 1
                        }
                    }, () => {
                        resolve(true)
                        wx.showToast({
                            title: '操作成功',
                            icon: 'success'
                        })
                        this.setData({ list: [], empty: true })
                    }, () => {
                        resolve()
                    })
                }
                resolve(true);
            })
        })
    },
    //点击全部加价、降价
    showModifyPricePopup(e) {
        if (this.data.list.length === 0) return wx.showToast({
            title: '暂无商品',
            icon: 'none'
        })

        const { index } = e.currentTarget.dataset
        this.setData({
            radio: Number(index),
            showModifyPrice: true
        })
    },
    //批量调价类型改变
    changeSource(e) {
        this.setData({ sourceActive: e.detail })
    },
    //批量改价输入框失焦事件
    inputBlurModifyPrice(e) {
        let value = this.formatter(e.detail.value)
        this.setData({ ModifyPrice: value ? value : '' })
    },
    //确定批量改价
    confirmModifyPrice() {
        if (!this.data.ModifyPrice) {
            return this.setData({
                ModifyPriceErr: true
            })
        }

        this.setData({ modifyPriceLoading: true })

        const from = ['cost', 'purchase'][this.data.sourceActive]

        this.request({
            url: '/supplier/product/batchPrice',
            method: 'POST',
            data: {
                type: this.data.radio,
                price: this.data.ModifyPrice.toString(),
                from
            }
        }, () => {
            wx.showToast({
                title: `全部${this.data.radio === 1 ? '加价' : '降价'}成功`,
                icon: 'success'
            })
            this.getList(true)
            this.setData({
                showModifyPrice: false,
                ModifyPrice: ''
            })
        }, () => {
            wx.showToast({
                title: `全部${this.data.radio === 1 ? '加价' : '降价'}失败`,
                icon: 'error'
            })
        }, () => {
            this.setData({ modifyPriceLoading: false })
        })
    },
    //禁止前往商品详情（防止输入框失焦时误触）
    prohibitToDetail() {
        this.data.enableToDetail = false
        this.delay(() => {
            this.data.enableToDetail = true
        })
    },
    pageBack() {
        wx.navigateBack()
    },
})